package com.zenithmind.chat.controller;

import com.zenithmind.chat.pojo.dto.ChatGroupDTO;
import com.zenithmind.chat.pojo.query.ChatGroupQuery;
import com.zenithmind.chat.pojo.vo.ChatGroupVO;
import com.zenithmind.chat.pojo.vo.ChatUserVO;
import com.zenithmind.chat.service.ChatGroupService;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import java.util.List;

/**
 * 群组管理控制器 - 遵循单一职责原则
 * 只负责群组管理的HTTP接口处理
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/chat/groups")
@RequiredArgsConstructor
@Validated
@Tag(name = "群组管理", description = "群组相关接口")
public class ChatGroupController {

    private final ChatGroupService chatGroupService;

    @PostMapping
    @Operation(summary = "创建群组", description = "创建新的群组")
    public Result<String> createGroup(@Valid @RequestBody ChatGroupDTO dto) {
        String userId = UserContext.getUserId();
        String groupId = chatGroupService.createGroup(dto, userId);
        return Result.success(groupId);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询群组列表", description = "分页查询当前用户的群组列表")
    public Result<PageResult<ChatGroupVO>> getGroupPage(@Valid ChatGroupQuery query) {
        String userId = UserContext.getUserId();
        query.setUserId(userId); // 设置当前用户ID
        PageResult<ChatGroupVO> result = chatGroupService.getGroupPage(query);
        return Result.success(result);
    }

    @GetMapping("/{groupId}")
    @Operation(summary = "查询群组详情", description = "根据群组ID查询群组详细信息")
    public Result<ChatGroupVO> getGroupById(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId) {
        String userId = UserContext.getUserId();
        ChatGroupVO group = chatGroupService.getGroupById(groupId, userId);
        return Result.success(group);
    }

    @PutMapping("/{groupId}")
    @Operation(summary = "更新群组信息", description = "更新指定群组的基本信息")
    public Result<Boolean> updateGroup(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @Valid @RequestBody ChatGroupDTO dto) {
        String userId = UserContext.getUserId();
        Boolean result = chatGroupService.updateGroup(groupId, dto, userId);
        return Result.success(result);
    }

    @DeleteMapping("/{groupId}")
    @Operation(summary = "解散群组", description = "解散指定的群组")
    public Result<Boolean> deleteGroup(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId) {
        String userId = UserContext.getUserId();
        Boolean result = chatGroupService.deleteGroup(groupId, userId);
        return Result.success(result);
    }

    @PostMapping("/{groupId}/join")
    @Operation(summary = "加入群组", description = "申请加入指定群组")
    public Result<Boolean> joinGroup(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @Parameter(description = "加入理由") @RequestParam(required = false) String reason) {
        String userId = UserContext.getUserId();
        Boolean result = chatGroupService.joinGroup(groupId, userId, reason);
        return Result.success(result);
    }

    @PostMapping("/{groupId}/leave")
    @Operation(summary = "退出群组", description = "退出指定群组")
    public Result<Boolean> leaveGroup(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId) {
        String userId = UserContext.getUserId();
        Boolean result = chatGroupService.leaveGroup(groupId, userId);
        return Result.success(result);
    }

    @PostMapping("/{groupId}/invite")
    @Operation(summary = "邀请用户加入群组", description = "邀请指定用户加入群组")
    public Result<Boolean> inviteUsers(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @RequestBody @NotEmpty List<String> userIds) {
        String userId = UserContext.getUserId();
        Boolean result = chatGroupService.inviteUsers(groupId, userIds, userId);
        return Result.success(result);
    }

    @PostMapping("/{groupId}/remove")
    @Operation(summary = "移除群组成员", description = "从群组中移除指定成员")
    public Result<Boolean> removeMembers(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @RequestBody @NotEmpty List<String> userIds) {
        String userId = UserContext.getUserId();
        Boolean result = chatGroupService.removeMembers(groupId, userIds, userId);
        return Result.success(result);
    }

    @GetMapping("/{groupId}/members")
    @Operation(summary = "查询群组成员", description = "分页查询群组成员列表")
    public Result<PageResult<ChatUserVO>> getGroupMembers(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "角色") @RequestParam(required = false) Integer role,
            @Parameter(description = "关键词") @RequestParam(required = false) String keyword,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "20") Integer pageSize) {
        PageResult<ChatUserVO> result = chatGroupService.getGroupMembers(groupId, status, role, keyword, pageNum, pageSize);
        return Result.success(result);
    }

    @PutMapping("/{groupId}/transfer")
    @Operation(summary = "转让群主", description = "将群主权限转让给其他成员")
    public Result<Boolean> transferOwnership(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @Parameter(description = "新群主用户ID") @RequestParam @NotBlank String newOwnerId) {
        String userId = UserContext.getUserId();
        Boolean result = chatGroupService.transferOwnership(groupId, newOwnerId, userId);
        return Result.success(result);
    }

    @PutMapping("/{groupId}/members/{memberId}/role")
    @Operation(summary = "设置成员角色", description = "设置群组成员的角色")
    public Result<Boolean> setMemberRole(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @Parameter(description = "成员ID") @PathVariable @NotBlank String memberId,
            @Parameter(description = "角色") @RequestParam Integer role) {
        String userId = UserContext.getUserId();
        Boolean result = chatGroupService.setMemberRole(groupId, memberId, role, userId);
        return Result.success(result);
    }

    @GetMapping("/my")
    @Operation(summary = "查询我的群组", description = "查询当前用户加入的所有群组")
    public Result<List<ChatGroupVO>> getMyGroups(
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        String userId = UserContext.getUserId();
        List<ChatGroupVO> groups = chatGroupService.getUserGroups(userId, status);
        return Result.success(groups);
    }

    @GetMapping("/search")
    @Operation(summary = "搜索群组", description = "根据关键词搜索公开群组")
    public Result<List<ChatGroupVO>> searchGroups(
            @Parameter(description = "关键词") @RequestParam @NotBlank String keyword,
            @Parameter(description = "群组类型") @RequestParam(required = false) Integer groupType) {
        List<ChatGroupVO> groups = chatGroupService.searchGroups(keyword, groupType);
        return Result.success(groups);
    }

    @GetMapping("/{groupId}/check-permission")
    @Operation(summary = "检查群组权限", description = "检查当前用户在群组中的权限")
    public Result<Boolean> checkPermission(
            @Parameter(description = "群组ID") @PathVariable @NotBlank String groupId,
            @Parameter(description = "权限类型") @RequestParam @NotBlank String permission) {
        String userId = UserContext.getUserId();
        Boolean hasPermission = chatGroupService.checkPermission(groupId, userId, permission);
        return Result.success(hasPermission);
    }
}
